import JEditableTable from '@/components/jeecg/JEditableTable'
import { VALIDATE_NO_PASSED, getRefPromise, validateFormAndTables } from '@/utils/JEditableTableUtil'
import { httpAction, getAction } from '@/api/manage'

export const JEditableTableMixin = {
  components: {
    JEditableTable
  },
  props:['EnhanceJS'],
  data () {
    return {
      title: '操作',
      visible: false,
      form: this.$form.createForm(this),
      confirmLoading: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 6 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 18 }
      }
    }
  },
  methods: {
    updatechanges(val){
      if(val == 'update'){
        this.editAfter()
      }else{
        this.visible = false
      }
    },
    /** 获取所有的editableTable实例 */
    getAllTable () {
      if (!(this.refKeys instanceof Array)) {
        throw this.throwNotArray('refKeys')
      }
      const values = this.refKeys.map(key => getRefPromise(this, key))
      return Promise.all(values)
    },

    /** 遍历所有的JEditableTable实例 */
    eachAllTable (callback) {
      // 开始遍历
      this.getAllTable().then(tables => {
        tables.forEach((item, index) => {
          if (typeof callback === 'function') {
            callback(item, index)
          }
        })
      })
    },

    /** 当点击新增按钮时调用此方法 */
    add () {
      if (typeof this.addBefore === 'function') this.addBefore()
      // 默认新增空数据
      let rowNum = this.addDefaultRowNum
      if (typeof rowNum !== 'number') {
        rowNum = 1
        console.warn('由于你没有在 data 中定义 addDefaultRowNum 或 addDefaultRowNum 不是数字，所以默认添加一条空数据，如果不想默认添加空数据，请将定义 addDefaultRowNum 为 0')
      }
      this.eachAllTable((item) => {
        item.add(rowNum)
      })
      if (typeof this.addAfter === 'function') this.addAfter(this.model)
      this.edit({})
    },
    /** 当点击了编辑（修改）按钮时调用此方法 */
    edit (record) {
      if (typeof this.editBefore === 'function') this.editBefore(record)
      this.visible = true
      this.activeKey = this.refKeys[0]
      this.form.resetFields()
      this.model = Object.assign({}, record)
      if (typeof this.editAfter === 'function') this.editAfter(this.model)
    },
    /** 关闭弹窗，并将所有JEditableTable实例回归到初始状态 */
    close () {
      this.visible = false
      this.eachAllTable((item) => {
        item.initialize()
      })
      this.$emit('close')
    },

    /** 查询某个tab的数据 */
    requestSubTableData (url, params, tab, success) {
      tab.loading = true
      getAction(url, params).then(res => {
        tab.dataSource = res.data || []
        typeof success === 'function' ? success(res) : ''
      }).finally(() => {
        tab.loading = false
      })
    },
    /** 发起请求，自动判断是执行新增还是修改操作 */
    // request (formData) {
    //   let url = this.url.add; let method = 'post'
    //   if (this.model.id) {
    //     url = this.url.edit
    //     method = 'put'
    //   }
    //   this.confirmLoading = true
    //   httpAction(url, formData, method).then((res) => {
    //     if (res.success) {
    //       this.$message.success(res.msg)
    //       this.$emit('ok')
    //       this.close()
    //     } else {
    //       this.$message.warning(res.msg)
    //     }
      //   }).finally(() => {
      //     this.confirmLoading = false
    //   })
    // },
    /** 发起请求，自动判断是执行新增还是修改操作 */
    request (formData) {
      console.log(this.EnhanceJS )
      if(this.EnhanceJS == undefined){

        let url = this.url.add; let method = 'post'
        if (this.model.id) {
          url = this.url.edit
          method = 'put'
        }
        this.confirmLoading = true
        httpAction(url, formData, method).then((res) => {
          if (res.success) {
            this.$message.success(res.msg)
            this.$emit('ok')
            this.close()
          } else {
            this.$message.warning(res.msg)
          }
        }).finally(() => {
          this.confirmLoading = false
        })
      }else{
        // 为了验证这部分的代码，编辑新增的控制加的方法
        this.formData = formData
        let url = ''; let method = ''
        if (this.model.id) {
          url = this.url.edit
          method = 'put'
          if(this.EnhanceJS.afterEdit){
          //编辑之前
            let Obj = eval(this.EnhanceJS.afterEdit)
            new Obj(this)
          }else{
            this.modalFrom(url,formData,method)
          }
        }else{
          url = this.url.add
          method = 'post'
          if( this.EnhanceJS.afterAdd ){
            //新增之前
            let Obj = eval(this.EnhanceJS.afterAdd)
            new Obj(this)
          }else{
            this.modalFrom(url,formData,method)
          }
        }
      }
      
    },

    // httpurl  提交表单的api formData提交的数据  method1提交的类型
    modalFrom(httpurl,formData,method1){ 
      const that = this
      that.confirmLoading = true
      httpAction(httpurl,that.formData,method1).then((res)=>{
        if (res.success) {
          this.$message.success(res.msg)
          this.$emit('ok')
          this.close()
        } else {
          this.$message.warning(res.msg)
        }
      }).finally(() => {
        that.confirmLoading = false;
      })
    },

  // 提交验证 url验证接口api  method验证类型    httpurl表单提交url method表单提交类型
    modalFunAjaxOnchang(url,method,httpurl,method1){
      const that = this;
      let p = new Promise((resolve, reject) => {
        httpAction(url,that.formData,method).then((res)=>{
          if(res.success){
            resolve(true);
          }else{
            reject(res.msg)
          }
          }).finally(() => {
            that.confirmLoading = false;
        })
      })
       p.then((data) => {
          that.modalFrom(httpurl,that.formData,method1)
        },(err) => {
           that.$message.warning(err);
        }
      ); 
    },

    /* --- handle 事件 --- */

    /** ATab 选项卡切换事件 */
    handleChangeTabs (key) {
      // 自动重置scrollTop状态，防止出现白屏
      getRefPromise(this, key).then(editableTable => {
        editableTable.resetScrollTop()
      })
    },
    /** 关闭按钮点击事件 */
    handleCancel () {
      this.close()
    },
    /** 确定按钮点击事件 */
    handleOk () {
      /** 触发表单验证 */
      this.getAllTable().then(tables => {
        /** 一次性验证主表和所有的次表 */
        return validateFormAndTables(this.form, tables)
      }).then(allValues => {
        if (typeof this.classifyIntoFormData !== 'function') {
          throw this.throwNotFunction('classifyIntoFormData')
        }
        const formData = this.classifyIntoFormData(allValues)
        // 发起请求
        return this.request(formData)
      }).catch(e => {
        if (e.error === VALIDATE_NO_PASSED) {
          // 如果有未通过表单验证的子表，就自动跳转到它所在的tab
          this.activeKey = e.index == null ? this.activeKey : this.refKeys[e.index]
        } else {
          console.error(e)
        }
      })
    },

    /* --- throw --- */

    /** not a function */
    throwNotFunction (name) {
      return `${name} 未定义或不是一个函数`
    },

    /** not a array */
    throwNotArray (name) {
      return `${name} 未定义或不是一个数组`
    }

  }
}
